/*
 * @Author: Wangjun
 * @Date: 2021-07-19 19:31:56
 * @LastEditTime: 2023-07-20 13:38:58
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \golib\autoroute\minauth\user.go
 * hnxr
 */
package minauth

import (
	"encoding/json"
	"os"
)

var users *Users

const (
	userFilePath = "user.dat"
)

func Init(defaultUser func() (user, passwd string)) {
	users = new(Users)
	users.init(defaultUser)
}

/**
 * @description: 保存账号信息
 * @return {*}
 */
func Save() (err error) {
	if users != nil {
		err = users.Save()
	}
	return
}

func GetUsers() *Users {
	return users
}

type User struct {
	Name string //用户名
	Pwd  string //密码
}

type Users struct {
	users   []*User
	mapUser map[string]*User
}

func (m *Users) Save() (err error) {
	data, err := json.MarshalIndent(m.users, "", " ")
	if err != nil {
		return
	}
	err = os.WriteFile(userFilePath, data, 0644)
	return
}

func (m *Users) init(defaultUser func() (user, passwd string)) {
	m.mapUser = map[string]*User{}
	data, err := os.ReadFile(userFilePath)
	if err != nil {
		if defaultUser != nil {
			name, pwd := defaultUser()
			m.AddUser(name, pwd, true)
		}
		return
	}
	err = json.Unmarshal(data, &m.users)
	if err != nil {
		if defaultUser != nil {
			name, pwd := defaultUser()
			m.AddUser(name, pwd, true)
		}
		return
	}
	for _, user := range m.users {
		m.mapUser[user.Name] = user
	}
}

func (m *Users) GetUser(name string) *User {
	user := m.mapUser[name]
	return user
}

func (m *Users) AddUser(name, pwd string, needHash bool) {
	user := m.mapUser[name]
	if needHash {
		pwd = Hash(pwd)
	}
	if user == nil {
		user = new(User)
		user.Name = name
		m.mapUser[user.Name] = user
		m.users = append(m.users, user)
	}
	user.Pwd = pwd
}
